package ar.com.tallerdos.smartdinner.sync;

import java.util.List;

import ar.com.tallerdos.smartdinner.business.ProductoBusiness;
import ar.com.tallerdos.smartdinner.business.RubroBusiness;
import ar.com.tallerdos.smartdinner.business.SubrubroBusiness;
import ar.com.tallerdos.smartdinner.model.Producto;
import ar.com.tallerdos.smartdinner.model.Rubro;
import ar.com.tallerdos.smartdinner.model.Subrubro;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class RubrosSincronizador extends Tarea {

    private static final String RUBROS_SERVICE = "consultarRubros.php";
    private static final String SUBRUBROS_SERVICE = "consultarSubRubros.php";
    private static final String PRODUCTOS_SERVICE = "consultarProductos.php";

    @Override
    public Integer realizarTarea() {
	Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
		.create();

	String rubrosJson = llamarWebService(SERVER_URL + "/" + RUBROS_SERVICE);
	List<Rubro> rubros = gson.fromJson(rubrosJson,
		new TypeToken<List<Rubro>>() {
		}.getType());

	String subrubrosJson = llamarWebService(SERVER_URL + "/"
		+ SUBRUBROS_SERVICE);
	List<Subrubro> subrubros = gson.fromJson(subrubrosJson,
		new TypeToken<List<Subrubro>>() {
		}.getType());

	String productosJson = llamarWebService(SERVER_URL + "/"
		+ PRODUCTOS_SERVICE);
	List<Producto> productos = gson.fromJson(productosJson,
		new TypeToken<List<Producto>>() {
		}.getType());

	if (rubros != null) {
	    for (Rubro r : rubros) {
		for (Subrubro sr : subrubros) {
		    for (Producto p : productos) {
			if (p.getSubrubro_id() == sr.getId()) {
			    p.setSubrubro(sr);
			    p.setSubrubro_id(-1);
			    sr.getProductos().add(p);
			}
		    }
		    if (sr.getRubro_id() == r.getId()) {
			sr.setRubro(r);
			sr.setRubro_id(-1);
			r.getSubrubros().add(sr);
		    }
		}
	    }
	    for (Rubro r : rubros) {
		RubroBusiness.createOrUpdate(r);
	    }
	    
	}

	if (subrubros != null) {
	    for (Subrubro sr : subrubros) {
		SubrubroBusiness.createOrUpdate(sr);
	    }
	}
	if (productos != null) {
	    for (Producto p : productos) {
		ProductoBusiness.createOrUpdate(p);
	    }
	}

	return null;
    }

}
